package com.woniuxy.student.controller;

import java.io.IOException;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.springframework.web.bind.annotation.RestController;

import com.woniuxy.student.util.WebSocketUtil;


/**
 * @Author: lishuwei
 * @Date: 2020/7/18
 * @description:
 */

@RestController
@ServerEndpoint("/WebSocketController/{idFrom}")
public class WebSocketController {
	// 建立连接时自动执行
	@OnOpen
	public void onopen(@PathParam("idFrom") int idFrom, Session session) {

		WebSocketUtil.users.put(idFrom, session);


	}

	// 收到消息，转发给所有人
	@OnMessage // 参数二浏览器发送的消息
	public void onmessage(@PathParam("idFrom") int idFrom,String message) {
	    String[] msgList=message.split("<<<<");
	    int msgType=Integer.parseInt(msgList[0]);
	    int idTo=Integer.parseInt(msgList[1]);
	    int qaid=Integer.parseInt(msgList[2]);
	    String newMsg=msgType+">>>>"+idFrom+">>>>"+qaid+">>>>";
	    for (int i=3;i<msgList.length;i++){
            newMsg+=msgList[i];
        }
		WebSocketUtil.sendMessage(idTo,newMsg);

	}

	@OnClose
	public void onclose(@PathParam("idFrom") int idFrom, Session session) {

		WebSocketUtil.users.remove(idFrom);

		try {
			session.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
